package com.fzy.common.db;

import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DBUtil {
    private DBUtil() {
    }

    private static Connection con = null;
    private static ResultSet rs = null;
    private static PreparedStatement pstmt = null;

    /**
     * 获取connection
     */
    public static Connection getConnection() {
        try {
            //1.加载驱动
            Class.forName("com.mysql.jdbc.Driver");
            //2.创建连接
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/yyy", "root", "123456");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return con;
    }

    /**
     * 关闭conection
     */
    public static void close(Connection con) {
        try {
            if (null != rs) {
                rs.close();
            }
            if (null != pstmt) {
                pstmt.close();
            }
            if (null != con) {
                con.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                    if (pstmt != null) {
                        pstmt.close();
                    }
                    if (con != null) {
                        con.close();
                    }
                }
            } catch (SQLException e1) {
            }
        }
    }

    /**
     * 新增
     */
    public static int insert(String sql, Object[] params) {
        return executeUpdate(sql, params);
    }

    /**
     * 更新
     */
    public static int update(String sql, Object[] params) {
        return executeUpdate(sql, params);
    }

    /**
     * 删除
     */
    public static int delete(String sql, Object[] params) {
        return executeUpdate(sql, params);
    }


    public static int executeUpdate(String sql, Object[] params) {
        Connection con = getConnection();
        int result = 0;
        try {
            pstmt = con.prepareStatement(sql);
            if (params != null) {
                for (int i = 0; i < params.length; i++) {
                    pstmt.setObject(i + 1, params[i]);
                }
            }
            result = pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            close(con);
        }
        return result;
    }

    /**
     * 查询单个对象返回map
     */
    public static Map<String, Object> get(String sql, Object[] params) {
        Connection con = getConnection();
        Map<String, Object> result = null;
        try {
            pstmt = con.prepareStatement(sql);
            if (params != null) {
                for (int i = 0; i < params.length; i++) {
                    pstmt.setObject(i + 1, params[i]);
                }
            }
            rs = pstmt.executeQuery();
            ResultSetMetaData data = rs.getMetaData();
            result = new HashMap<>(data.getColumnCount());
            while (rs.next()) {
                for (int i = 0; i <= data.getColumnCount(); i++) {
                    String c = data.getColumnName(i + 1);
                    Object v = rs.getObject(c);
                    result.put(c, v);
                }
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            close(con);
        }
        return result;
    }

    /**
     * 查询列表返回List<map>
     */
    public static List<Map<String, Object>> findList(String sql, Object[] params) {
        Connection con = getConnection();
        List<Map<String, Object>> result = new ArrayList<>();
        try {
            PreparedStatement pstmt = con.prepareStatement(sql);
            if (params != null) {
                for (int i = 0; i < params.length; i++) {
                    pstmt.setObject(i + 1, params[i]);
                }
            }
            rs = pstmt.executeQuery();
            ResultSetMetaData data = rs.getMetaData();
            while (rs.next()) {
                Map<String, Object> map = new HashMap<>(data.getColumnCount());
                for (int i = 0; i <= data.getColumnCount(); i++) {

                    String c = data.getColumnName(i + 1);
                    Object v = rs.getObject(c);
                    map.put(c, v);
                }
                result.add(map);
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            close(con);
        }
        return result;
    }

    /**
     * 通过反射机制查询单条记录
     */
    public <T> T get(String sql, Object[] params, Class<T> cls) throws Exception {
        T resultObject = null;
        int index = 1;
        pstmt = con.prepareStatement(sql);
        if (params != null) {
            for (int i = 0; i < params.length; i++) {
                pstmt.setObject(index++, params[i]);
            }
        }
        rs = pstmt.executeQuery();
        ResultSetMetaData metaData = rs.getMetaData();
        int colsLen = metaData.getColumnCount();
        while (rs.next()) {
            //通过反射机制创建一个实例  
            resultObject = cls.newInstance();
            for (int i = 0; i < colsLen; i++) {
                String colsName = metaData.getColumnName(i + 1);
                Object colsValue = rs.getObject(colsName);
                if (colsValue == null) {
                    colsValue = "";
                }
                Field field = cls.getDeclaredField(colsName);
                //打开javabean的访问权限
                field.setAccessible(true);
                field.set(resultObject, colsValue);
            }
        }
        return resultObject;

    }


    /**
     * 通过反射机制查询多条记录
     */
    public <T> List<T> findList(String sql, Object[] params, Class<T> cls) throws Exception {
        List<T> list = new ArrayList<T>();
        int index = 1;
        pstmt = con.prepareStatement(sql);
        if (params != null) {
            for (int i = 0; i < params.length; i++) {
                pstmt.setObject(index++, params[i]);
            }
        }
        rs = pstmt.executeQuery();
        ResultSetMetaData metaData = rs.getMetaData();
        int colsLen = metaData.getColumnCount();
        while (rs.next()) {
            //通过反射机制创建一个实例  
            T resultObject = cls.newInstance();
            for (int i = 0; i < colsLen; i++) {
                String colsName = metaData.getColumnName(i + 1);
                Object colsValue = rs.getObject(colsName);
                if (colsValue == null) {
                    colsValue = "";
                }
                Field field = cls.getDeclaredField(colsName);
                //打开javabean的访问权限
                field.setAccessible(true);
                field.set(resultObject, colsValue);
            }
            list.add(resultObject);
        }
        return list;
    }
}